﻿using System;
using NHibernate;
using TestBat.IModels.Domain;
using TestBat.IModels.Repositories;
using TestBat.Models.Domain;

namespace TestBat.Models.Repositories
{
    public class ScheduleRepository : Repository<ISchedule, Guid>, IScheduleRepository
    {   
        /// <summary>
        /// constructor
        /// </summary>
        /// <param name="session">The NHibernate-sessionfactory</param>
        public ScheduleRepository(ISessionFactory sessionFactory)
            : base(sessionFactory)
        {
        }

        public override ISchedule GetByID(Guid ID)
        {
            return Session.Get<Schedule>(ID);
        }

        // HACK: whole override is a hack because NHibernate's Session.Refresh() doesn't refresh collections (added and removed entities)
        public override void Refresh(ISchedule o)
        {
            if (Session.Contains(o))
            { // entity is part of this session
                var id = Session.GetIdentifier(o);
                //foreach (IScheduleTask i in o.Tasks)
                //{
                //    try
                //    {
                //        var id2 = Session.GetIdentifier(i);
                //        Session.Evict(i);
                //        Session.Load(i, id2);
                //    }
                //    catch { }
                //}
                Session.Evict(o);
                Session.Clear(); // HACK: the session still thinks it is dirty, so we clear it fully; not sure which side-effects this introduces
                Session.Load(o, id);

            }
            else
            { // entity is not part of this session
                try
                {
                    Session.Refresh(o); // try, if entity is detached
                }
                catch (UnresolvableObjectException)
                { // object is transient anyway
                    return;
                }
            }
        }

        public void MakeTransient(IScheduleTraineeGroup traineeGroup)
        {
            Session.Delete(traineeGroup);
        }

        public void MakeTransient(IScheduleTask task)
        {
            Session.Delete(task);
        }
    }
}
